from celery import bootsteps
from kombu import Consumer, Exchange, Queue
from models.silo import MassLog
from . import app
from utils.decorators import with_application
from extensions import db
from log import logger


class BaseCustomReplyConsumerStep(bootsteps.ConsumerStep):
    """消费者基类通过集成方式描写消费者"""

    exchange = Exchange(name='micro-events', type='topic', durable=True)

    @property
    def queue(self):
        raise NotImplementedError

    def get_consumers(self, channel):
        return [Consumer(channel=channel, queues=[self.queue], callbacks=[self.callback], accept=['json'])]

    def callback(self, body, customer):
        raise NotImplementedError


class WechatFeedbackConsumer(BaseCustomReplyConsumerStep):
    
    @property
    def queue(self):
        return Queue(name='silo',
                     exchange=self.exchange,
                     routing_key='silo.daemon.backend.#')
    
    @with_application
    def callback(self, body, message):
        message.ack()
        logger.info(body)
        
        msg_id = body.get('MsgID')
        if not msg_id:
            logger.info('不是想要的消息')
            return

        logger.info('wx_msg_id: {}'.format(msg_id))
        
        MassLog.query.filter(MassLog.wx_msg_id == msg_id).update({
            MassLog.total_count: body.get('TotalCount'),
            MassLog.filter_count: body.get('FilterCount'),
            MassLog.send_count: body.get('SentCount'),
            MassLog.error_count: body.get('ErrorCount'),
            MassLog.state: body.get('Status'),
        })
        
        db.session.commit()
        logger.info('群发日志已经更新: {}'.format(body.get('MsgID')))


app.steps['consumer'].add(WechatFeedbackConsumer)
